﻿using System;
using System.Linq;
using System.Xml.Linq;
using System.Net.Http;
using System.Globalization;
using OurDailyBread.Helpers;
using Windows.UI.Xaml.Media.Imaging;

namespace OurDailyBread.Model
{
    public class ImageDataService : IImageDataService
    {
        private static readonly string PhotoImagesUri = "http://www.istartedsomething.com/bingimages/";
        private static readonly Uri PhotoImagesUri2 = new Uri("http://feeds.feedburner.com/bingimages");

        public async void GetData(DateTime today, Action<Object, Exception> callback)
        {
            // Use this to connect to the actual data service
            try
            {
                string hrefStr = "#" + today.ToString("yyyyMMdd") + "-us";
                string getResults = await HttpService.Get(new Uri(PhotoImagesUri));

                int usImage = getResults.IndexOf(hrefStr);
                string startMarker = "data-original=\"";
                int imageUrlStart = getResults.IndexOf("data-original=\"", usImage) + startMarker.Length;
                int imageUrlEnd = getResults.IndexOf("&w", imageUrlStart);
                string imageUrl = PhotoImagesUri + getResults.Substring(imageUrlStart, imageUrlEnd - imageUrlStart) + "&w=1024";

                callback(imageUrl, null);
            }
            catch (Exception ex)
            {
                callback(null, ex);
            }
        }

        public async void GetData2(DateTime today, Action<Object, Exception> callback)
        {
            // Use this to connect to the actual data service
            try
            {
                // try to get the daily image from archive first.  This can give us different images if users browse different dates
                string hrefStr = "#" + today.ToString("yyyyMMdd") + "-us";
                string getResults = await HttpService.Get(new Uri(PhotoImagesUri));

                int usImage = getResults.IndexOf(hrefStr);
                string startMarker = "data-original=\"";
                int imageUrlStart = getResults.IndexOf("data-original=\"", usImage) + startMarker.Length;
                int imageUrlEnd = getResults.IndexOf("&w", imageUrlStart);
                string imageUrl = PhotoImagesUri + getResults.Substring(imageUrlStart, imageUrlEnd - imageUrlStart) + "&w=1024";

                using (var client = new HttpClient())
                {
                    HttpResponseMessage msg = await client.GetAsync(new Uri(imageUrl));
                    if (msg.IsSuccessStatusCode && msg.Content.Headers.ContentLength != 0)
                    {
                        callback(imageUrl, null);
                        return;
                    }
                }

                // if the archive doesn't exist, try the RSS feed route
                imageUrl = null;
                // try another url
                string results = await HttpService.Get(PhotoImagesUri2);
                XDocument doc = XDocument.Parse(results);
                var items = doc.Element("rss")
                                .Element("channel")
                                .Elements("item")
                                .ToList();
                string countryCode = CultureInfo.CurrentUICulture.Name.ToUpperInvariant();
                var urls = items
                    .Where(s =>
                            s.Element("enclosure")
                            .Attribute("url")
                            .Value
                            .Contains("_" + countryCode)
                            ||
                            s.Element("enclosure")
                            .Attribute("url")
                            .Value
                            .Contains("_EN-US")      
                            ||
                            s.Element("enclosure")
                            .Attribute("url")
                            .Value
                            .Contains("_ROW")  // new zealand photo
                            )
                    .Select(p =>
                        p.Element("enclosure")
                            .Attribute("url")
                            .Value)
                    .ToList();
                if (urls.Count > 0)
                {
                    using (var client = new HttpClient())
                    {
                        for (int i=0; i<urls.Count; i++)
                        {
                            HttpResponseMessage msg = await client.GetAsync(new Uri(urls[i]));
                            if (msg.IsSuccessStatusCode && msg.Content.Headers.ContentLength != 0)
                            {
                                imageUrl = urls[i];
                                break;
                            }
                        }
                        
                    }
                }
                callback(imageUrl, null);
            }
            catch (Exception ex)
            {
                callback(null, ex);
            }
        }

        public string GetData3(DateTime today)
        {
            string imagUrlFormat = "http://d626yq9e83zk1.cloudfront.net/files/{0}/";
            string imageUrl = string.Format(imagUrlFormat, today.Year);

            if (today.Month < 10)
            {
                imageUrl += '0';
            }
            imageUrl += today.Month + "/";

            string imageUrlFormatTail = "{0}-770x425.jpg";
            string imageUrlTail = string.Format(imageUrlFormatTail, today.Day);

            if (today.Day < 10)
                imageUrl += '0';
            imageUrl += imageUrlTail;

            return imageUrl;
        }

    }
}